package com.fingard.dsp.bank.directbank.payease01;

import java.util.Date;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.FailCode;
import com.fingard.dsp.bank.directbank.PaymentState;
import com.fingard.dsp.bank.directbank.bankInterface.IRealTime;
import com.fingard.dsp.bank.reqrespobj.single.ReqQrySingle;
import com.fingard.dsp.bank.reqrespobj.single.ReqSingle;
import com.fingard.dsp.bank.reqrespobj.single.RetAtsSingle;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.fingard.net.ConnState;
import com.fingard.text.StringHelper;

/** F.cruise
 *  首信易单笔实时代扣
 */
public class PayEase01RealTime extends PayEase01Base implements IRealTime {
	/**
	 * 代扣交易请求提交
	 */
	public RetAtsSingle d_9108_RealTimeRec(ReqSingle p_req9108)	throws Exception {
		RetAtsSingle retAts = new RetAtsSingle(p_req9108.reqHeader);
		RetAtsSglDetail tmpRetDetail = new RetAtsSglDetail();
		
		try {
			ActSetItem actItem = getBankConfig().getActSetItem(p_req9108.singleDetail.recAct, "");
			if (actItem == null) {
				tmpRetDetail.respCode = "0";
				tmpRetDetail.respInfo = "未找到账号"+p_req9108.singleDetail.recAct+"对应的商户配置信息";
				tmpRetDetail.transAmt = p_req9108.singleDetail.payAmount;
				tmpRetDetail.reqSeqID = p_req9108.singleDetail.askNumber;
				tmpRetDetail.transState = PaymentState.FAIL_Payment;
				tmpRetDetail.payInfoCode = "E9981";
				
				retAts.writeRetDetail(tmpRetDetail);
				return retAts;
			}
			
			StringBuilder req_Json = new StringBuilder();
			// 拼接提现交易请求JSON
			req_Json.append("{");
			req_Json.append("\"transCode\":\"TRS001008\",");// 交易码
			req_Json.append("\"reqTime\":\"" + Format.DateTimeFormat.format(new Date()) + "\","); // 请求时间 yyyy-mm-dd hh:mm:ss
			req_Json.append("\"operationCode\":\"" + getBankConfig().getMapValueByKey("operationCode", "10") + "\",");// 操作码
			req_Json.append("\"serlNum\":\"" + p_req9108.singleDetail.askNumber + "\",");// 流水号
			req_Json.append("\"authId\":\"\",");// 授权码
			req_Json.append("\"user\":\"" + actItem.merchantId + "\",");// P2P网站用户注册名
			req_Json.append("\"mobile\":\"" + p_req9108.singleDetail.cellPhone + "\",");// 用户手机号
			req_Json.append("\"idType\":\"" + convertCertTypeToBank(p_req9108.singleDetail.certType) + "\",");// 开户证件类型
			req_Json.append("\"id\":\"" + p_req9108.singleDetail.certNum + "\",");// 开户证件号码
			req_Json.append("\"accName\":\"" + p_req9108.singleDetail.payName + "\",");// 开户名
			req_Json.append("\"accProvince\":\"\",");// 省
			req_Json.append("\"accCity\":\"\",");// 市
			req_Json.append("\"accBank\":\"" + p_req9108.singleDetail.payBankName + "\",");// 开户银行名称
			req_Json.append("\"accNum\":\"" + p_req9108.singleDetail.payAct + "\","); // 开户银行账号
			
			// //账号类型     00 -- 卡；  01 -- 存折	     默认00
			if (p_req9108.singleDetail.cardType.equals("1")) {
				req_Json.append("\"accType\":\"" + "01" + "\",");
			} else {
				req_Json.append("\"accType\":\"" + "00" + "\",");
			}
			
			// 账号类别  PR-对私	PU-对公	默认PR
			if (p_req9108.singleDetail.isPrivate.equals("1")) {
				req_Json.append("\"accProp\":\"" + "PR" + "\",");
			} else {
				req_Json.append("\"accProp\":\"" + "PU" + "\",");
			}
			
			req_Json.append("\"amount\":\"" + p_req9108.singleDetail.payAmount + "\",");// 金额
			req_Json.append("\"pin\":\"\",");// 账户密码
			req_Json.append("\"groupId\":\"" + actItem.merchantId + "\",");// P2P商户编号
			req_Json.append("\"branchId\":\"0\",");// P2P子公司编号
			req_Json.append("\"merdata1\":\"" + p_req9108.singleDetail.authAgNum + "\",");// 预留字段1  暂时用于填写客户协议编号
			req_Json.append("\"merdata2\":\"\"");// 预留字段2
			req_Json.append("}");
			
			// 加密前JSON
			WriteBankLogLn("加密前JSON:" + req_Json.toString());
			
			// 发送首信易
			String[] tmpStrRet = sendToBank("receivables", req_Json.toString(), actItem);
			
			// 解析首信易返回
			if (tmpStrRet[0].length() == 0) {
				// 解密前返回数据
				WriteBankLogLn2("解密前JSON:" + tmpStrRet[1]);
				
				// 解密JSON (DES解密)
				String tmpRespJson = EncDecUtil.dec(actItem.saltKey, tmpStrRet[1]);
				
				// 首信易返回JSON (解密后JSON)
				WriteBankLogStep3(tmpRespJson);
				
				if (tmpRespJson.startsWith("{")) {
					String[] tmpMsgs =tmpRespJson.split(",");
					
					String returnCode = "";
					String returnMsg = "";
					String transAmt = "";
					
					/*
					 * 循环遍历JSON，获取JSON串中的有效信息
					 */
					for(int i=0;i<tmpMsgs.length;i++){
						String[] values = tmpMsgs[i].split(":");
						if(values.length>1){
							
							if(values[0].indexOf("returnCode")>=0){
								returnCode = values[1].replace("\"", "").replace("{", "").replace("}", "").replace("[", "").replace("]", ""); 
							}else if(values[0].indexOf("returnMsg")>=0){
								returnMsg = values[1].replace("\"", "").replace("{", "").replace("}", "").replace("[", "").replace("]", ""); 
							}else if(values[0].indexOf("amount")>=0){
								String amount = values[1].replace("\"", "").replace("{", "").replace("}", "").replace("[", "").replace("]", ""); 
								transAmt = Format.DecimalAmtFormat.format(Double.parseDouble(amount));
							}
						}
					}
					
					tmpRetDetail.respCode = "0";
					tmpRetDetail.respInfo = returnMsg;
					tmpRetDetail.reqSeqID = p_req9108.singleDetail.askNumber;
					tmpRetDetail.transAmt = transAmt;
					tmpRetDetail.transState = returnCode;
					tmpRetDetail.payInfoCode = tmpRetDetail.transState;
				} else {
					tmpRetDetail.respCode = "-1";
					tmpRetDetail.respInfo = tmpRespJson;
				}
			} else if (tmpStrRet[0].equals(ConnState.FAIL) || tmpStrRet[0].equals(FailCode.E9981)) {
				tmpRetDetail.respCode = "0";
				tmpRetDetail.respInfo = tmpStrRet[1];
				tmpRetDetail.reqSeqID = p_req9108.singleDetail.askNumber;
				tmpRetDetail.transAmt = p_req9108.singleDetail.payAmount;
				tmpRetDetail.transState = PaymentState.FAIL_Payment;
				tmpRetDetail.payInfoCode = tmpStrRet[0];
			} else {
				tmpRetDetail.respCode = "-1";
				tmpRetDetail.respInfo = tmpStrRet[1];
			}
		} catch (Exception e) {
			tmpRetDetail.respCode = "-1";
			tmpRetDetail.respInfo = e.getMessage();
			e.printStackTrace();
		}
		
		if (tmpRetDetail.respCode.equals("-1") && StringHelper.isNullOrEmpty(tmpRetDetail.reqSeqID)) {
			tmpRetDetail.reqSeqID = p_req9108.singleDetail.askNumber;
		}
		
		retAts.writeRetDetail(tmpRetDetail);
		return retAts;
	}

	/**
	 * 单笔实时代扣状态查询
	 */
	public RetAtsSingle d_9144_QryRealTimeRec(ReqQrySingle p_req9144)	throws Exception {
		/**
		 * 首信易有异步通知接口，该接口无效
		 */
		return null;
	}
}
